package com.helloandroid.services

import androidx.core.content.edit
import com.helloandroid.MyApplication
import com.helloandroid.tools.GUtils
import com.helloandroid.tools.IntentValue
import com.helloandroid.tools.MyTimeUtils

class LocalHbyInfo(
        var lastHbyPlayTimeMs: Long = 0L, // 上次玩红包雨的时间
        var lastTimeMs_Remind: Long = 0L, // 上次红包雨提醒的时间
        var bFlagRemind: Boolean = true, // 玩家是否打开了提醒
) {

    companion object {
        const val PrefHby = "s_pref_hby"
        const val KeyHbyLastPlayTime = "key_last_play_time"
        const val KeyHbyLastRemindTime = "key_last_time_remind"
        const val KeyFlagHby = "key_flag_hby"

        // 红包雨通知时间
        const val Hby_Mid = 20 * GUtils.OneHourMs
        const val Hby_Begin = Hby_Mid - 5 * GUtils.OneMinutes
        const val Hby_End = Hby_Mid + 5 * GUtils.OneMinutes
    }

    fun init() {
        val pref = MyApplication.getPerference(PrefHby)
        bFlagRemind = pref.getBoolean(KeyFlagHby, true)
        lastHbyPlayTimeMs = pref.getLong(KeyHbyLastPlayTime, 0L)
        lastTimeMs_Remind = pref.getLong(KeyHbyLastRemindTime, 0L)
    }

    fun check(service: ServerService, curTimeMs: Long): Boolean {

        val timeMs = MyTimeUtils.getTodayOffsetMs(curTimeMs)
        if (timeMs in Hby_Begin..Hby_End) {
            // find
            // 1. 玩家开了提醒
            // 2.今天还没有提醒过
            // 3. 今天是否已经玩过
            if (bFlagRemind) {
                val curDayTime = MyTimeUtils.dayTimeString(curTimeMs)
                val remindDayTime = MyTimeUtils.dayTimeString(lastTimeMs_Remind)
                if (curDayTime != remindDayTime) {
                    // 今天还没提醒
                    val lastPlayDayTime = MyTimeUtils.dayTimeString(lastHbyPlayTimeMs)
                    if (curDayTime != lastPlayDayTime) {
                        // 今天还没玩
                        service.sendRemindNotify("抢红包啦！", "下雨啦,下红包雨啦!赶紧来抢红包啦!", IntentValue.Int_Hby)
                        MyApplication.getPerference(PrefHby).edit(commit = true) {
                            putLong(KeyHbyLastRemindTime, curTimeMs)
                        }
                        lastTimeMs_Remind = curTimeMs
                    }
                }
            }
        }
        return false
    }

    fun clearData() {
        MyApplication.getPerference(PrefHby).edit(commit = true) {
            clear()
        }
    }

    fun savePlayHbyTime(time:Long){
        MyApplication.getPerference(PrefHby).edit(commit = true){
            putLong(KeyHbyLastPlayTime,time)
        }
        lastHbyPlayTimeMs = time
    }

    fun updateFlag(newFlag:Boolean){
        if (newFlag != bFlagRemind){
            bFlagRemind = newFlag
            MyApplication.getPerference(PrefHby).edit(commit = true){
                putBoolean(KeyFlagHby,newFlag)
            }
        }
    }
}